var resErr = require('../lib/util.js').resErr;
var async = require('async');
var DB = require("../lib/db_mysql").DB;

exports.role_list = function(req,res){
  var sql_text = "SELECT * FROM t_sys_role";
  var limit = parseInt(req.param("limit") || req.param("pageSize") ||'20');
  var page  = parseInt(req.param("page") || req.param("pageNum") || '1');
  if(req.param("sort")){
    sql_text += " order by " + req.param("sort") + " " + req.param("dir");
  }
  var db = new DB();
  db.queryPage(sql_text,null,page,limit,function(err,result){
    if(err) return resErr(res, err);
    return res.json(result);
  });
}

exports.role_edit = function(req, res) {
  var role_id = req.param('role_id');
  var role_name = req.param('role_name');
  if(!role_name) {
    return res.json({success:false,msg:'角色名称不能为空！'});
  }
  var role_key = req.param('role_key');
  if(!role_key) {
    return res.json({success:false,msg:'角色编码不能为空！'});
  }
  var role_enable = req.param('role_enable');
  var role_desc = req.param('role_desc');
  var params = [];
  params.push(role_name);
  params.push(role_key);
  params.push(role_desc);
  params.push(role_enable);
  var db = new DB();
  if(!role_id){
    var sql_text = "insert  into t_sys_role(role_name,role_key,role_desc,role_enable) values(?,?,?,?)"
    db.query(sql_text,params,function(err,datas){
      if(err) return resErr(res, err);
      return res.json({success:true,msg:'角色信息添加成功！'});
    });
  }else{
    var sql_text = "update t_sys_role set role_name=?,role_key=?,role_desc=?,role_enable=? where role_id=?";
    params.push(role_id);
    db.query(sql_text,params,function(err,datas){
      if(err) return resErr(res, err);
      return res.json({success:true,msg:'角色信息修改成功！'});
    });
  }
}

exports.role_check = function(req,res){
  var role_key = req.param('role_key');
  if(role_key){
    var params = [];
    var sql_text = "select count(1) counter from t_sys_role where role_key=?"
    params.push(role_key);
    var db = new DB();
    db.query(sql_text,params,function(err,datas){
      if(err) return resErr(res, err);
      if(datas.length > 0 && datas[0].counter > 0){
        return res.json({success:false,msg:'该资源编码已经被占用！'});
      } else {
        return res.json({success:true,msg:'该资源编码可用！'});
      }
    });
  } else {
    return res.json({success:false,msg:'资源编码不能为空！'});
  }
}

exports.role_del = function(req,res){
  var role_id = req.param('role_id');
  var sqls = {
    'deleteUserRoleSQL': 'DELETE FROM t_sys_user_role WHERE role_id=?',
    'deleteResourceRoleSQL': 'DELETE FROM t_sys_resource_role WHERE role_id=?',
    'deleteRoleSQL': 'DELETE FROM t_sys_role WHERE role_id=?'
  };
  var tasks = ['deleteUserRoleSQL', 'deleteResourceRoleSQL', 'deleteRoleSQL'];
  role_id = parseInt(role_id);
  var tmp_params = [];
  tmp_params.push(role_id);
  var db = new DB();
  async.eachSeries(tasks, function (item, callback) {
      console.log(item + " ==> " + sqls[item]);
      db.query(sqls[item], tmp_params, function (err, datas) {
          if(err) return resErr(res, err);
          callback(null);
      });
  }, function (err) {
      if(err) return resErr(res, err);
      return res.json({success:true,msg:'角色删除成功！'});
  });
}

//根据角色ID，查找拥有该角色的用户列表
exports.role_users = function(req,res){
  var role_id = req.param('role_id');
  if(!role_id) return res.json({success:false,msg:'角色ID不能为空！'});
  var params = [];
  var sql_text = "SELECT * FROM t_sys_user WHERE status=0 AND user_id IN (SELECT user_id FROM t_sys_user_role WHERE role_id=?)";
  params.push(role_id);
  var limit = parseInt(req.param("limit") || req.param("pageSize") ||'20');
  var page  = parseInt(req.param("page") || req.param("pageNum") || '1');
  if(req.param("sort")){
    sql_text += " order by " + req.param("sort") + " " + req.param("dir");
  }
  var db = new DB();
  db.queryPage(sql_text,params,page,limit,function(err,result){
    if(err) return resErr(res, err);
    return res.json(result);
  })  
}

//解除用户授权
exports.role_removeuser = function(req, res){
  var user_id = req.param('user_id');
  var role_id = req.param('role_id');
  if(!user_id) return res.json({success:false,msg:'用户ID不能为空！'});
  if(!role_id) return res.json({success:false,msg:'角色ID不能为空！'});
  var sql = "delete from t_sys_user_role where user_id=? and role_id=?";
  var params = [];
  params.push(user_id);
  params.push(role_id);
  var db = new DB();
  db.query(sql,params,function(err,datas){
    if(err) return resErr(res, err);
    return res.json({success:true,msg:'解除授权成功！'});
  })
}

//给用户授予角色
exports.role_adduser = function(req,res){
  var role_id = req.param('role_id');
  var user_id = req.param('user_id');
  if(!user_id) return res.json({success:false,msg:'用户ID不能为空！'});
  if(!role_id) return res.json({success:false,msg:'角色ID不能为空！'});
  var params = [];
  var sql_text = "insert into t_sys_user_role(user_id,role_id) values(?,?)";
  params.push(user_id);
  params.push(role_id);
  var db = new DB();
  db.query(sql_text,params,function(err,datas){
    if(err) return resErr(res, err);
    return res.json({success:true,msg:'授权成功！'});
  })
}

//给角色授权
exports.role_addresource = function(req,res){
  var role_id = req.param('role_id');
  var resource_ids = req.param('resource_ids');
  var resource_id_ary = resource_ids.split(',');
  if(!resource_ids || resource_id_ary.length < 1) return res.json({success:false,msg:'资源ID不能为空！'});
  if(!role_id) return res.json({success:false,msg:'角色ID不能为空！'});
  var params = [];
  var sql_text = "delete from t_sys_resource_role where role_id=?";
  params.push(role_id);
  var db = new DB();
  db.query(sql_text,params,function(err,datas){
    if(err) return res.json({success:false,msg:JSON.stringify(err)});
    //批量操作
    async.eachSeries(resource_id_ary, function(resource_id, callback){
      if(resource_id){
        var sql = "insert into t_sys_resource_role(res_id,role_id) values(?,?)";
        var tmp_params = [];
        tmp_params.push(resource_id);
        tmp_params.push(role_id);
        db.query(sql,tmp_params,function(err,datas){
          if(err) return callback(err);
          callback(null);
        });
      } else {
        callback(null);
      }
    }, function(err){
      if(err) return resErr(res, err);
      return res.json({success:true,msg:'角色授权成功！'});
    });
  })

}